package com.ang.juc.n4.t1;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock同一个对象
 * 当lock被锁，其他线程会等待，当lock对象unlock或者lock的Condition await的时候，锁会被释放
 */

public class T {
    private final ReentrantLock lock = new ReentrantLock();

    public void methodA() {
        System.out.println("A获取锁:   "+lock.hashCode());
        lock.lock();
        System.out.println("A得到锁:   "+lock.hashCode());
        try {
            // 执行受保护的代码段
            System.out.println(Thread.currentThread().getName() + ":    Method A is executing.");
            // 模拟一些工作
            Thread.sleep(5000);
            System.out.println("A释放锁");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();
        }
    }

    public void methodB() {
        System.out.println("B获取锁:   "+lock.hashCode());
        lock.lock();
        System.out.println("B得到锁:   "+lock.hashCode());
        try {
            // 执行受保护的代码段
            System.out.println(Thread.currentThread().getName() + ":    Method B is executing.");
            // 模拟一些工作
            Thread.sleep(5000);
            System.out.println("B释放锁");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        T t = new T();
        new Thread(() -> {
            t.methodA();
        }).start();

        new Thread(() -> {
            t.methodB();
        }).start();

//        new Thread(() -> {
//            new t().methodA();
//        }).start();
//
//        new Thread(() -> {
//            new t().methodB();
//        }).start();
    }
}
